package com.liliya.controller;


import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.liliya.common.lang.Result;
import com.liliya.entity.Blog;
import com.liliya.service.BlogService;
import com.liliya.shiro.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 关注公众号：MarkerHub
 * @since 2021-05-07
 */
@RestController
@RequestMapping("/blog")
public class BlogController {

    @Autowired
    BlogService blogService;


    //一个简单的分页接口
    @GetMapping("/blogs")
    public Result blog(@RequestParam(defaultValue = "1") int currentPage){
        Page<Blog> page = new Page(currentPage, 5);
        IPage<Blog> pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("created"));

        return Result.succ(pageData);
    }
    @GetMapping("/detail/{id}")
    public Result detail(@PathVariable int id){
        Blog blog = blogService.getById(id);
        Assert.notNull(blog,"该blog不存在");
        return Result.succ(blog);
    }


    //blog的编辑
    @RequiresAuthentication
    @PostMapping("/edit")
    public Result detail(@Validated @RequestBody Blog blog){

        Blog temp = null;
        if (blog.getId()!=null){
            temp = blogService.getById(blog.getId());
            Assert.isTrue(temp.getUserId()==ShiroUtil.getProfile().getId(),"你没有权限编辑");
        }else {
            temp = new Blog();
            temp.setStatus(0);
            temp.setCreated(LocalDateTime.now());
            temp.setUserId(ShiroUtil.getProfile().getId());
        }

        BeanUtils.copyProperties(blog,temp,"id","userId","created","status");
        blogService.saveOrUpdate(temp);

        return Result.succ("OK");
    }



}
